package arduino;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.Vector;

public class DriverMessageQueue implements Runnable{
		private MessageQueue messageQueue;
		Robot awtRobot;
		Driver parent;

		// constructors
		DriverMessageQueue(){
			messageQueue = null;
			
			try {
				awtRobot = new Robot();
			} catch( AWTException e ){
				e.printStackTrace();
			}
		}

		DriverMessageQueue( MessageQueue msgQ ){
			this();
			messageQueue = msgQ;
		}
		
		DriverMessageQueue( MessageQueue msgQ, Driver drv ){
			this( msgQ );
			parent = drv;
		}
		
		// accessor + mutator
		public void SetMessageQueue( MessageQueue msgQ ){
			messageQueue = msgQ;
		}
		
		public void SetParentDriver( Driver drv ){
			parent = drv;
		}
		
		// main handler thread
		public void run(){
			Vector<MyMessage> myQueue ;
			int prevSourceID = -1;
			
			while( true ){
				// empty the event vector since we are going to put a new event there
				// event.clear() ;
				// get all existing messages
				// this thread i.e. consumer thread will go to sleep if there are 
				// no existing messages
				myQueue = messageQueue.GetAllMessages();
				
				for( MyMessage msg:myQueue ){
					//System.out.println( "msgQ source: " + msg.sourceID + " message:" + msg.message );
					
					if( msg.sourceID == 0 ){	// break
						awtRobot.keyPress( KeyEvent.VK_END );
						awtRobot.keyRelease( KeyEvent.VK_END );
					}else if( msg.sourceID == 1 ){	// accelerate
						awtRobot.keyPress( KeyEvent.VK_HOME );
						awtRobot.keyRelease( KeyEvent.VK_HOME );
					}else if( msg.sourceID == 2 ){	// Light
						// preproc
						int i = msg.message.indexOf( 'L' );  
						if( i != -1 )
							msg.message = msg.message.substring( i + 1 );
						
						// proc
						if( parent != null )
							parent.setAmbient( Double.valueOf( msg.message ) );
						
						awtRobot.keyPress( KeyEvent.VK_PAGE_UP );
						awtRobot.keyRelease( KeyEvent.VK_PAGE_UP );
												
					}else if( msg.sourceID == 3 ){	// Engine Break
						awtRobot.keyPress( KeyEvent.VK_0 );
						awtRobot.keyRelease( KeyEvent.VK_0 );
						
					}else if( msg.sourceID == 4 ){	// Temperature
						// preproc
						int i = msg.message.indexOf( 'T' );  
						if( i != -1 )
							msg.message = msg.message.substring( i + 1 );
						
						// proc
						if( parent != null )
							parent.setTemperature( Double.valueOf( msg.message ) );
						
						awtRobot.keyPress( KeyEvent.VK_PAGE_DOWN );
						awtRobot.keyRelease( KeyEvent.VK_PAGE_DOWN );
						
					}else if( msg.sourceID == 5 ){	// airbag
						awtRobot.keyPress( KeyEvent.VK_ESCAPE );
						awtRobot.keyRelease( KeyEvent.VK_ESCAPE );
						
					}
					
				} // for(MyPressureMessage msg:myQueue){
			} //while(true)
		} //public void processMessagesInQueue(){
}
